package com.lzx.hbh_system.service.xqzhxxgl.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.hbh_system.bo.filter.xqzhxxgl.HouseholdInfoFilter;
import com.lzx.hbh_system.bo.xqzhxxgl.BuildingInfo;
import com.lzx.hbh_system.bo.xqzhxxgl.HouseInfo;
import com.lzx.hbh_system.bo.xqzhxxgl.HouseholdInfo;
import com.lzx.hbh_system.bo.zffyxxgl.ExpanseInfo;
import com.lzx.hbh_system.bo.zffyxxgl.HouseholdAExpanse;
import com.lzx.hbh_system.bo.zffyxxgl.PayInfo;
import com.lzx.hbh_system.bo.zffyxxgl.PayInfoDetail;
import com.lzx.hbh_system.bo.xqzhxxgl.HeatingInfo;
import com.lzx.hbh_system.dto.xqzhxxgl.HouseholdInfoDto;
import com.lzx.hbh_system.mapper.xqzhxxgl.HouseInfoMapper;
import com.lzx.hbh_system.mapper.xqzhxxgl.HouseholdInfoMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.ExpanseInfoMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.HouseholdAExpanseMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.PayInfoDetailMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.PayInfoMapper;
import com.lzx.hbh_system.mapper.xqzhxxgl.HeatingInfoMapper;
import com.lzx.hbh_system.service.xqzhxxgl.HouseHoldInfoService;
import com.lzx.hbh_system.util.SnowFlakeUtil;
import com.lzx.hbh_system.util.TurnDateToStringUtil;
import com.lzx.hbh_system.util.responseEntity.RespOutMsgHeader;
import com.lzx.hbh_system.util.responseEntity.ResponseView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class HouseHoldInfoServiceImpl extends ServiceImpl<HouseholdInfoMapper, HouseholdInfo> implements HouseHoldInfoService {
    @Autowired
    private HouseholdInfoMapper householdInfoMapper;
    @Autowired
    private HouseInfoMapper houseInfoMapper;
    @Autowired
    private HeatingInfoMapper heatingInfoMapper;
    @Autowired
    private HouseholdAExpanseMapper householdAExpanseMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private ExpanseInfoMapper expanseInfoMapper;
    @Autowired
    private PayInfoDetailMapper payInfoDetailMapper;
    @Override
    public ResponseView queryAllHouseHoldInfoPageFilter(HouseholdInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("00",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        // 逻辑实现
        // 初始化分页对象
        Page<HouseholdInfoDto> householdInfoDtoPage = new Page<>(filter.getPageIndex(),filter.getPageSize());
        // 查询
        IPage<HouseholdInfoDto> householdInfoDtoIPage = householdInfoMapper.selectAllHouseholdInfoPageFilter(householdInfoDtoPage,filter);
        // 处理结果集
        List<HouseholdInfoDto> householdInfoDtos = householdInfoDtoIPage.getRecords();
        // 返回响应消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success(householdInfoDtos.size(),"查询成功！"));
        // 设置返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("dataArray", householdInfoDtos.toArray());
        map.put("currentPage",householdInfoDtoIPage.getCurrent());
        map.put("totalsData",householdInfoDtoIPage.getTotal());
        responseView.setMain(map);
        return responseView;
    }

    @Override
    public ResponseView queryAllHouseHoldInfoList() {
        // 初始化
        ResponseView responseView = new ResponseView();
        List<HouseholdInfo> householdInfos = householdInfoMapper.selectList(null);
        List<Map<String,Object>> mapList = new ArrayList<>();
        householdInfos.forEach(item ->{
            Map<String,Object> map = new HashMap<>();
            map.put("householdId",item.getId());
            map.put("householdName",item.getHouseholdName());
            mapList.add(map);
        });
        // 返回消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("查询成功"));
        responseView.setMain(mapList.toArray());
        return responseView;
    }

    @Override
    public ResponseView addOneHouseHoldInfo(HouseholdInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("03",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        HouseholdInfo householdInfo = filter.getHouseholdInfo();
        String key = SnowFlakeUtil.getId(); // 生成雪花ID
        householdInfo.setId(key); // 主键
        householdInfo.setCreateTime(TurnDateToStringUtil.getTime());
        householdInfo.setValiFlag("1"); // 有效标识
        // 注册住户房屋信息
        HouseInfo houseInfo = createHouseInfo(filter);
        householdInfo.setHouseCode(houseInfo.getId()); // 设置房屋编号
        // 注册住户供热信息
        HeatingInfo heatingInfo = createHeatingInfo(filter,key);
        householdInfo.setHeatingCode(heatingInfo.getId()); // 设置供热信息编号
        // 注册住户费用项目信息
        createExpanseInfo(filter,key);
        // 保存数据库
        householdInfoMapper.insert(householdInfo);
        // 响应结果
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("添加成功！"));
        return responseView;
    }

    @Override
    public ResponseView modifyOneHouseHoldInfo(HouseholdInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("02",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        // 实现逻辑
        HouseholdInfo householdInfo = filter.getHouseholdInfo();
        householdInfo.setUpdateTime(TurnDateToStringUtil.getTime()); // 设置修改时间
        householdInfoMapper.updateById(householdInfo);
        // 响应结果
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("修改成功！"));
        return responseView;
    }

    @Override
    public ResponseView dropBatchHouseHoldInfo(HouseholdInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("01",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        List<String> householdInfoIdList = filter.getHouseholdInfoIdList();
        // 逻辑实现
        householdInfoMapper.deleteBatchIds(householdInfoIdList);
        // 暂未做关联删除 - 保护测试数据
        // 返回消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("删除成功！"));
        return responseView;
    }

    /**
     * 生成住户房屋信息
     * @param filter
     * @return
     */
    public HouseInfo createHouseInfo(HouseholdInfoFilter filter){
        // 初始化一个住户房屋信息
        HouseInfo houseInfo = new HouseInfo();
        String key = SnowFlakeUtil.getId(); // 生成雪花key
        houseInfo.setId(key); // 设置主键信息
        houseInfo.setCreateTime(TurnDateToStringUtil.getTime());
        houseInfo.setHouseArea(filter.getHouseArea()); // 设置住户房屋房号
        houseInfo.setHouseNumber(filter.getHouseNumber()); // 设置住户房屋建筑面积
        houseInfo.setBuildingCode(filter.getHouseholdInfo().getBuildingCode()); // 设置住户楼号编号
        houseInfo.setValiFlag("1"); // 默认有效
        houseInfoMapper.insert(houseInfo);
        return houseInfo;
    }

    /**
     * 生成住户供热信息
     * @param filter
     * @return
     */
    public HeatingInfo createHeatingInfo(HouseholdInfoFilter filter,String householdCode){
        // 初始化一个住户供热信息
        HeatingInfo heatingInfo = new HeatingInfo();
        String key = SnowFlakeUtil.getId(); // 生成雪花key
        heatingInfo.setId(key); // 设置主键信息
        heatingInfo.setHouseholdCode(householdCode); // 设置关联住户的编号
        heatingInfo.setHeatEquipmentSettingFlag("0"); // 默认供热设备未安装
        heatingInfo.setHeatArea(filter.getHeatingArea()); // 设置供热面积
        heatingInfo.setValiFlag("1"); // 默认有效
        // 保存信息
        heatingInfoMapper.insert(heatingInfo);
        return heatingInfo;
    }

    /**
     * 生成 住户 - 费用项目 关联中间信息
     * @param filter
     * @param HouseHoldkey
     */
    public void createExpanseInfo(HouseholdInfoFilter filter,String HouseHoldkey){
        List<String> expanseIdList = filter.getExpanseIdList(); // 拿到住户对应的费用项目ID
        expanseIdList.forEach(expanseId -> {
            // 初始化一个住户-费用项目中间信息对象
            HouseholdAExpanse householdAExpanse = new HouseholdAExpanse();
            householdAExpanse.setHouseHoldId(HouseHoldkey); // 设置关联住户编号
            householdAExpanse.setExpanseId(expanseId); // 设置关联的费用项目编号
            householdAExpanse.setValiFlag("1"); // 设置默认有效
            // 生成支付费用信息实体
            createPayInfo(expanseId,HouseHoldkey,filter);
            // 保存信息
            householdAExpanseMapper.insert(householdAExpanse);
        });
    }

    /**
     * 生成支付信息
     * @param expanseId
     * @param HouseHoldkey
     */
    public void createPayInfo(String expanseId,String HouseHoldkey,HouseholdInfoFilter filter){
        // 获取每个费用项目的收费信息
        QueryWrapper<ExpanseInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",expanseId);
        ExpanseInfo expanseInfo = expanseInfoMapper.selectOne(queryWrapper);
        // 项目费用信息
        String expenseModle = expanseInfo.getExpenseModle(); // 收费模式（1 平方 2 固定）
        BigDecimal late_fee = new BigDecimal("0.00"); // 是否超时扣费 - 滞纳金
        BigDecimal payReduction = new BigDecimal("0.00"); // 设定默认无优惠 - 优惠价格
        BigDecimal amount_receivable = new BigDecimal("0.00"); // 应收金额
        BigDecimal paid_in_amount = new BigDecimal("0.00"); // 实收金额
        if ("1".equals(expenseModle)){
            // 按平方
            BigDecimal Effective_heating_area = filter.getHeatingArea(); // 有效供热面积
            BigDecimal amount_price = expanseInfo.getAmountPrice(); // 价格
            // 应收金额 = 有效供热面积 * 价格 + 滞纳金 - 优惠价格
            amount_receivable = Effective_heating_area.multiply(amount_price).add(late_fee).subtract(payReduction);
        }
        // 初始化 支付信息对象
        PayInfo payInfo = new PayInfo();
        String key = SnowFlakeUtil.getId(); // 生成雪花key
        payInfo.setId(key); // 设置主键信息
        payInfo.setHouseholdCode(HouseHoldkey); // 设置关联的住户编号
        payInfo.setExpanseCode(expanseId); // 设置关联费用编号
        payInfo.setPayStatus("0"); // 设置支付状态
        int beginYear = Integer.parseInt(TurnDateToStringUtil.getTime("yyyy")); // 获得年度起始
        int addition = 1; // 年份增量
        Integer nextYear = beginYear + addition; // 获得年度截止
        payInfo.setYearsBegin(beginYear); // 设置年度起始
        payInfo.setYearsEnd(nextYear); // 设置年度截止
        payInfo.setPayReduction(payReduction); // 设置优惠价格
        payInfo.setAmountReceivable(amount_receivable); // 设置应收金额
        payInfo.setPaidInAmount(paid_in_amount); // 设置实收金额
        payInfo.setPayStatus("0");
        payInfo.setCrateTime(TurnDateToStringUtil.getTime()); // 设置数据创建时间
        payInfo.setValiFlag("1"); // 设置默认有效
        createPayinfoDetail(payInfo); // 生成支付信息详情
        // 保存信息
        payInfoMapper.insert(payInfo);
    }

    /**
     * 生成支付信息详情
     * @param payInfo
     * @return
     */
    public PayInfoDetail createPayinfoDetail(PayInfo payInfo){
        // 初始化一个支付信息详情信息对象
        PayInfoDetail payInfoDetail = new PayInfoDetail();
        String key = SnowFlakeUtil.getId(); // 生成雪花Key
        payInfoDetail.setId(key); // 设置主键信息
        payInfoDetail.setPayInfoCode(payInfo.getId()); // 设置关联的支付信息编号
        payInfoDetail.setValiFlag("1"); // 默认有效
        payInfoDetail.setReconciliationFlag("0"); // 默认未对账
        // 保存信息
        payInfoDetailMapper.insert(payInfoDetail);
        return payInfoDetail;
    }
    /**
     * 参数校验函数
     *  01 删除
     *  02 修改
     *  03 新增
     *  00 查询
     * @param filter
     * @return
     */
    public ResponseView checkParams(String operaType, HouseholdInfoFilter filter){
        // 初始化返回视图
        ResponseView responseView = new ResponseView();
        if (Objects.equals(operaType, "01") && filter.getHouseholdInfoIdList().size() == 0 ){
            responseView.setRespOutMsgHeader(RespOutMsgHeader.error("住户信息编号不能为空！"));
            return responseView;
        }
        else if (Objects.equals(operaType, "03")){
            if (filter.getExpanseIdList().size() == 0){
                responseView.setRespOutMsgHeader(RespOutMsgHeader.error("费用项目信息至少选择一种！"));
                return responseView;
            }
            if(filter.getHouseNumber() == null){
                responseView.setRespOutMsgHeader(RespOutMsgHeader.error("房号不能为空！"));
                return responseView;
            }
            if(filter.getHouseArea() == null){
                responseView.setRespOutMsgHeader(RespOutMsgHeader.error("房屋建筑面积不能为空！"));
                return responseView;
            }
            if(filter.getHeatingArea() == null){
                responseView.setRespOutMsgHeader(RespOutMsgHeader.error("房屋供热面积不能为空！"));
                return responseView;
            }
        }
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success());
        return responseView;
    }
}
